package com.huanbao.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.lang.Result;
import com.huanbao.entity.PersonalTask;
import com.huanbao.service.PersonalTaskService;
import com.huanbao.service.UserService;
import com.huanbao.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 任务大厅 前端控制器
 * </p>
 *
 * @author zq
 * @since 2021-04-29
 */
@Slf4j
@RestController
@RequestMapping("/task")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TaskController {

    private final PersonalTaskService taskService;

    private final UserService userService;

    @GetMapping("/list")
    public Result getTaskList() {
        List<PersonalTask> taskList = taskService.list(new QueryWrapper<PersonalTask>().notIn("state", 1));
        return Result.success(taskList);
    }

    @GetMapping("/receive/{taskId}")
    public Result receiveToTask(@PathVariable("taskId") Long taskId) {
        Long userId = ShiroUtil.getProfile().getId();
        PersonalTask byId = taskService.getById(taskId);
        byId.setState(1)
                .setUserId(userId);
        taskService.updateById(byId);
        String message = "接取任务" + byId.getContent() + "成功";
        userService.createMessage(message, userId);
        return Result.success(200, message, null);
    }

    @GetMapping("/finish/{id}")
    public Result finishTask(@PathVariable("id") Integer id) {
        Long userId = ShiroUtil.getProfile().getId();
        PersonalTask byId = taskService.getById(id);
        if (byId.getState() == 2) {
            return Result.fail("该任务已经完成，请勿重复点击。");
        }
        byId.setState(2);
        taskService.updateById(byId);
        if (byId.getTaskIntegral() != 0) {
            userService.IntegralModify(userId, 0, byId.getTaskIntegral());
        }
        String message = "您于" + LocalDateTime.now() + "完成任务：" + byId.getContent();
        userService.createMessage(message, userId);
        return Result.success(200, "已完成任务：" + byId.getContent(), null);
    }

}
